package evi.com.evi.receiver;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;

import cn.jpush.android.api.JPushInterface;
import evi.com.evi.R;
import evi.com.evi.activity.HomeActivity;
import evi.com.evi.application.MyApplication;
import evi.com.evi.utils.HeartBreakUtil;
import evi.com.evi.utils.SPUtil;

/**
 * Created by xuyu on 2017/3/28.
 */

public class JiguangReceiver extends BroadcastReceiver {

    private static final String TAG = "JPush";

    /*** 声音震动变量 **/
    private MediaPlayer mediaPlayer;
    private boolean playBeep;
    private static final float BEEP_VOLUME = 0.10f;
    private boolean vibrate;
    private Dialog soundDialog;
    // 作为配置铃声标识 1 第一个 2第二个 3第三个 此处可作为一个app的全局变量保存
    private static String soundType = "0";

    @Override
    public void onReceive(final Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        Log.e(TAG, "[JiguangReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));

        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            Log.e(TAG, "[JiguangReceiver] 接收Registration Id : " + regId);

            SPUtil.setString(context, "channelId", regId);
            HeartBreakUtil.sendHeartBreakPacket(null, null, null);

        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            Log.d(TAG, "[JiguangReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
            processCustomMessage(context, bundle);

        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            Log.d(TAG, "[JiguangReceiver] 接收到推送下来的通知");


            //接收到推送下来的通知。。。。。。。。。。。。。。。。。。。。。。。


            //播放音频
            soundType = SPUtil.getString(context, "soundType");
            if ("0".equals(soundType)) {
                SelectSoundPlay(context, R.raw.hongbao_gq);
            } else if ("1".equals(soundType)) {
                SelectSoundPlay(context, R.raw.hongbao_gx);
            } else if ("2".equals(soundType)) {
                SelectSoundPlay(context, R.raw.phonering);
            } else {
                SelectSoundPlay(context, R.raw.hongbao_gq);
            }

            //震动
            playBeepSoundAndVibrate(context);

            if (HomeActivity.isStart) {
                //刷新
                Activity homeActivity = MyApplication.getInstance().getActivity();
//                ((HomeActivity) homeActivity).showOne(2);
            } else {

            }

            int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
            Log.d(TAG, "[JiguangReceiver] 接收到推送下来的通知的ID: " + notifactionId);

        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            Log.d(TAG, "[JiguangReceiver] 用户点击打开了通知");

//            intent.setClass(context.getApplicationContext(), HomeActivity.class);
//            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            intent.putExtra("tag", 2);
//            context.getApplicationContext().startActivity(intent);


            //点击通知判断：在前台，刷新/过。不在前台，启动activity
            if (HomeActivity.isStart) {
                //刷新
                Activity homeActivity = MyApplication.getInstance().getActivity();
//                ((HomeActivity) homeActivity).showOne(2);

            } else {
                //            //打开自定义的Activity
                Toast.makeText(context, "跳转到主页面", Toast.LENGTH_LONG).show();
                Intent _intent = new Intent();
                _intent.setClass(context.getApplicationContext(), HomeActivity.class);
                _intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                _intent.putExtra("tag", 2);
                context.getApplicationContext().startActivity(_intent);
            }


        } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
            Log.d(TAG, "[JiguangReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
            //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..

        } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
            boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
            Log.w(TAG, "[JiguangReceiver]" + intent.getAction() + " connected state change to " + connected);
        } else {
            Log.d(TAG, "[JiguangReceiver] Unhandled intent - " + intent.getAction());
        }
    }

    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
                    Log.i(TAG, "This message has no Extra data");
                    continue;
                }

                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it = json.keys();

                    while (it.hasNext()) {
                        String myKey = it.next().toString();
                        sb.append("\nkey:" + key + ", value: [" +
                                myKey + " - " + json.optString(myKey) + "]");
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "Get message extra JSON error!");
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }

    //send msg to MainActivity
    private void processCustomMessage(Context context, Bundle bundle) {
//        if (MainActivity.isForeground) {
//            String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
//            String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
//            Intent msgIntent = new Intent(MainActivity.MESSAGE_RECEIVED_ACTION);
//            msgIntent.putExtra(MainActivity.KEY_MESSAGE, message);
//            if (!ExampleUtil.isEmpty(extras)) {
//                try {
//                    JSONObject extraJson = new JSONObject(extras);
//                    if (extraJson.length() > 0) {
//                        msgIntent.putExtra(MainActivity.KEY_EXTRAS, extras);
//                    }
//                } catch (JSONException e) {
//
//                }
//
//            }
//            context.sendBroadcast(msgIntent);
//        }
    }

    private MediaPlayer mPlayer;

    /***
     * 选择不同铃声 @ 用于不同地方调用 可自行封装在util里
     *
     * @param id
     */
    private void SelectSoundPlay(Context context, int id) {
        if (mPlayer != null) {
            mPlayer = null;
        }
        mPlayer = MediaPlayer.create(context, id);
        mPlayer.start();
//        mPlayer.release();
    }

    private static final long VIBRATE_DURATION = 200L;

    /****
     * 震动具体执行方法 @ 用于不同地方调用 可自行封装在util里
     */
    private void playBeepSoundAndVibrate(Context context) {
        if (playBeep && mediaPlayer != null) {
            mediaPlayer.start();
        }
        vibrate = SPUtil.getBoolean(context,"isSwitch");
        Log.e(TAG, "vibrate ========" + vibrate);
        if (vibrate) {
            Vibrator vibrator = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATE_DURATION);
        }
    }

}
